<?php

namespace App\Http\Controllers\Seller;

use App\Http\Controllers\Controller;
use App\Library\Mall\ShopTrait;
use App\Models\Item;
use App\Models\Order;
use App\Models\Shop;
use App\Models\Trade;
use Illuminate\Http\Request;

class ShopController extends Controller
{
    use ShopTrait;

    protected $sysMessageView = 'seller.message';
    /**
     * ShopController constructor.
     * @param Request $request
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->assign(['menu'=>'shop_set']);
    }

    /**
     * 店铺首页
     */
    public function index(){

        $shop = $this->user()->shop;
        if ($shop) {
            $content = $shop->content;
            $this->assign(compact('shop', 'content'));
            if ($shop->auth_status)
            {
                return $this->view('seller.shop.info');
            }
        } else {
            $this->assign([
                'shop'=>[
                    'shop_name'=>'',
                    'phone'=>'',
                    'logo'=>'',
                    'description'=>'',
                    'province'=>'',
                    'city'=>'',
                    'district'=>'',
                    'street'=>'',
                    'lng'=>'',
                    'lat'=>'',
                    'main_source'=>1,
                    'closed'=>0
                ] ,
                'content'=>[
                    'shop_id'=>0,
                    'content'=>''
                ]
            ]);
        }

        return $this->view('seller.shop.index');
    }

    /**
     * 店铺认证
     */
    public function auth(){
        $menu = 'shop_auth';
        $shop = $this->user()->shop;
        if ($shop)
        {
            $auth = $this->user()->shop->auth()->firstOrCreate([]);

            if ($auth->auth_status)
            {
                return $this->view('seller.shop.authed', compact('auth', 'menu'));
            } else {
                return $this->view('seller.shop.auth', compact('auth', 'menu'));
            }
        }
        return redirect('seller/shop');
    }

    public function unauthenticate()
    {
        return $this->view('seller.shop.unauthenticate');
    }


    /**
     * 店铺实时数据
     */
    public function live_data(){
        $shop = Shop::where('uid', $this->uid)->first();
        $itemCount = Item::where('uid', $this->uid)->count();
        $orderCount = Order::where('seller_uid', $this->uid)->count();
        $payerCount = Trade::where(['payee_uid'=>$this->uid, 'pay_status'=>1])->count();

        $this->assign([
            'shop'=>$shop,
            'itemCount'=>$itemCount,
            'orderCount'=>$orderCount,
            'payerCount'=>$payerCount
        ]);

        return $this->view('seller.shop.live_data');
    }
}
